﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data.Entity;
using System.Linq;
using System.Xml;
using CommonHelp;
using Core.Unity;
using Models;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace Services { 
    /// <summary>
    /// 灾害预警
    /// </summary>
    public class DisasterInfoService : Core.Unity.IInfoService {
        private EventHandler<ReceivedDataEventArgs> _ReceivedDataEvents;
        private List<DisasterInfo> _DataList;

        public event EventHandler<ReceivedDataEventArgs> AfterQueryData {
            add {
                _ReceivedDataEvents += value;
            }
            remove {
                _ReceivedDataEvents -= value;
            }
        }

        public void OnModelCreating(ref DbModelBuilder modelBuilder) {
            modelBuilder.Entity<DisasterInfo>().ToTable("WEBDATA_DISASTER");
        }

        public void QueryData() {
            string url = ConfigurationManager.AppSettings["QueryDisasterUrl"].ToString();
            HttpHelper http = new HttpHelper(url);
            http.GetAsync(AfterGetData);
        }

        private void AfterGetData(string responseString) {
            try {
                if (responseString == null) {
                    return;
                }
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(responseString);

                List<DisasterInfo> infos = new List<DisasterInfo>();
                for (int i = 0; i < doc.ChildNodes.Count; i++) {
                    var node = doc.ChildNodes[i];
                    if (node.NodeType == XmlNodeType.XmlDeclaration || node.NodeType == XmlNodeType.Comment) {
                        continue;
                    }
                    for (int j = 0; j < node.ChildNodes.Count; j++) {
                        var groupNode = node.ChildNodes[j];
                        foreach (XmlNode item in groupNode.ChildNodes) {
                            string jsonStr = JsonConvert.SerializeXmlNode(item, Newtonsoft.Json.Formatting.None, true);
                            jsonStr = jsonStr.Replace("\"@", "\"");
                            DisasterInfo info = JsonConvert.DeserializeObject<DisasterInfo>(jsonStr);
                            info.Type = groupNode.Name;
                            infos.Add(info);
                        }
                    }
                }

                _DataList = infos;

                if (_ReceivedDataEvents != null) {
                    _ReceivedDataEvents(this, new ReceivedDataEventArgs(infos));
                }
            }
            catch (Exception ex) {
                CommonHelp.LogHelper.Error(ex);
                if (_ReceivedDataEvents != null) {
                    _ReceivedDataEvents(this, new ReceivedDataEventArgs(ex));
                }
            }
        }

        public void SaveData(object data) {
            using (WebDataContext db = new WebDataContext()) {
                List<DisasterInfo> list = data as List<DisasterInfo>;
                DbSet<DisasterInfo> infos = db.Set<DisasterInfo>();
                foreach (var item in list) {
                    if (infos.Any(a => a.StationId == item.StationId)) {
                        continue;
                    }

                    infos.Add(item);
                }
                db.SaveChanges();
            }
        }
    }
}
